/**
 * App端相关操作
 */
import $store from '@/store'
import uniApi from '@/util/uniApi'
import {queryParse} from '../../lib/pageUtil'
import {tabBar} from '../../../pages.json'
import appUpdate from './appUpdate'
import platform from '@/util/platform'

// 获取服务供应商: https://uniapp.dcloud.net.cn/api/plugins/provider.html#
const getProvider = (service = '') => {
	// eslint-disable-next-line no-undef
	return new Promise((resolve, reject) => {
		if (!service) return reject('请传入服务名称')
		const serviceList = ['oauth', 'share', 'payment', 'push']
		if (!serviceList.includes(service)) return reject('服务名称错误')
		uni.getProvider({
			service,
			success: ({provider}) => {
				return resolve(provider)
			},
			fail: (err) => {
				return reject(err)
			}
		})
	})
}

// 检查APP版本更新
const checkUpdate = async () => {
	if (platform.os === 'android') {
		// 获取版本信息
		const {data} = await getVersion()
		if (!data) return
		// 获取当前APP版本信息
		plus.runtime.getProperty(plus.runtime.appid, (info) => {
			// 判断是否需要更新
			if (data.versionNum > info.versionCode) {
				// 判断是否若提示更新并忽略该版本
				if (data.upgradeType === 3 && $store('app').ignoreVersion === data.versionNum) return
				// 更新APP
				appUpdate(data)
			}
		})
	}
}

// App端检测网络状态变化
export const getNetworkStatusChange = () => {
	const LocalNetWorkType = $store('app').netWorkType
	uni.onNetworkStatusChange(function (res) {
		const {isConnected, networkType} = res
		if (LocalNetWorkType === networkType) return
		$store('app').setNetWorkType(isConnected ? networkType : '')

		if (!LocalNetWorkType && isConnected) {
			uniApi.toast({title: '网络已恢复连接', icon: 'none', duration: 3500})
			setTimeout(() => {
				// eslint-disable-next-line no-undef
				plus.runtime.restart()
			}, 1000)
			return
		}
		if (LocalNetWorkType && !isConnected) {
			uniApi.toast({title: '请检查您的网络连接状态', icon: 'none', duration: 3500})
			return
		}
	})
}
export default {
	getProvider,
	checkUpdate
}
